package com.linln.component.thymeleaf.utility;

import com.linln.common.utils.EhCacheUtil;
import com.linln.modules.system.domain.Dict;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.message.service.MessageTypeService;
import com.linln.common.utils.SpringContextUtil;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;

/**
 * 字典提取工具对象
 * @author 小懒虫
 * @date 2018/8/14
 */
public class MessageTypeUtil {

    private static Cache messageTypeCache = EhCacheUtil.getMessageTypeCache();

    /**
     * 获取字典值集合
     * @param label 字典标识
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> value(String label){
        Map<String, String> value = null;
        Element dictEle = messageTypeCache.get(label);
        if(dictEle != null){
            value = (Map<String, String>) dictEle.getObjectValue();
        }else {
        	MessageTypeService messageTypeService = SpringContextUtil.getBean(MessageTypeService.class);
        	MessageType typenew=new MessageType();
        	typenew.setPid(0L); 
        	ExampleMatcher matcher = ExampleMatcher.matching().
                     withMatcher("pid", match -> match.contains());
             // 获取部门列表
             Example<MessageType> example = Example.of(typenew, matcher);
             Sort sort = new Sort(Sort.Direction.ASC, "num");
        	List<MessageType> typelist = messageTypeService.getListByExample(example, sort);
            if(typelist != null && typelist.size()>0){
                 value = new LinkedHashMap<>();
                for (MessageType type : typelist) {
                     if(type!=null){
                        value.put(type.getId()+"", type.getTitle()
                        		);
                    }
                }
                messageTypeCache.put(new Element("message", value));
            }
        }
        return value;
    }

    /**
     * 根据选项编码获取选项值
     * @param label 字典标识
     * @param code 选项编码
     */
    public static String keyValue(String label, String code){
        Map<String, String> list = MessageTypeUtil.value(label);
        if(list != null){
            return list.get(code);
        }else{
            return "";
        }
    }

    /**
     * 封装数据状态字典
     * @param status 状态
     */
    public static String dataStatus(Byte status){
        String label = "MESSAGETYPE_STATUS";
        return MessageTypeUtil.keyValue(label, String.valueOf(status));
    }

    /**
     * 清除缓存中指定的数据
     * @param label 字典标识
     */
    public static void clearCache(String label){
        Element dictEle = messageTypeCache.get(label);
        if (dictEle != null){
        	messageTypeCache.remove(label);
        }
    }
}
